package ca.michaelmaguire.server.mobiledownload.server;

import javax.servlet.http.HttpServletRequest;

public class HeaderUtilities {

	/**
	 * Attempts to retrieve a named String value from an HttpRequest parameters
	 * or headers, saving it to the session.
	 * 
	 * If not in the request, checks for it saved to the session.
	 * 
	 * Always gives precedence to the requests parameter, then the header value,
	 * finally the stored session value.
	 * 
	 * The value will always be saved to the session.
	 * 
	 * @param aParameterName
	 * @param aHttpServletRequest
	 * @return null if not set as either a parameter or a session variable.
	 */
	public static String getAndSaveParameterOrHeader(
			HttpServletRequest aHttpServletRequest, String aParameterName) {

		// First try to retrieve parameter from the request itself.
		String returnString = aHttpServletRequest.getParameter(aParameterName);
		if (null == returnString) {
			// Now look for a header.
			returnString = aHttpServletRequest.getHeader(aParameterName);
		}

		if (null == returnString) {

			returnString = (String) aHttpServletRequest.getSession()
					.getAttribute(aParameterName);
		} else {

			// Save the header as a session parameter in case we need it later.
			if (null != returnString) {
				aHttpServletRequest.getSession().setAttribute(aParameterName,
						returnString);
			}
		}

		return returnString;
	}

	public static String produceMimeTypeForFileName(String aFileName) {

		for (int i = 0; i < ENDINGS_TO_MIME_TYPES.length; ++i) {
			String[] mapping = ENDINGS_TO_MIME_TYPES[i];
			if (aFileName.toLowerCase().endsWith(mapping[0])) {
				return mapping[1];
			}
		}

		return null;
	}

	private static final String[][] ENDINGS_TO_MIME_TYPES = {
			{ ".jad", HeaderConstants.JAD_MIME_TYPE },
			{ ".jar", HeaderConstants.JAR_MIME_TYPE }, { ".jpg", "image/jpeg" } };
}
